package com.kingdee.eas.custom.assure.client;

import java.awt.event.ActionEvent;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.ctrl.kdf.table.KDTSelectBlock;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.ui.face.CoreUIObject;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.assure.ExternalAssureBizBillFactory;
import com.kingdee.eas.custom.assure.ExternalAssureBizBillInfo;
import com.kingdee.eas.custom.assure.IExternalAssureBizBill;
import com.kingdee.eas.fm.ctl.AssureBillCollection;
import com.kingdee.eas.fm.ctl.AssureBillFactory;
import com.kingdee.eas.fm.ctl.AssureBillInfo;
import com.kingdee.eas.fm.ctl.IAssureBill;
import com.kingdee.eas.rptclient.newrpt.util.MsgBox;
import com.kingdee.util.StringUtils;

/**
 * 
 * Title: ExternalAssureBillListUICTEx
 * <p>
 * Description: 对外担保业务列表
 * 
 * @author yacong_liu Email:yacong_liu@kingdee.com
 * @date 2019-6-18 & 下午05:59:54
 * @since V1.0
 */
public class ExternalAssureBizBillListUICTEx extends ExternalAssureBizBillListUI {

    private static final long serialVersionUID = -7173070755688349918L;

    private static final Logger logger = CoreUIObject.getLogger(ExternalAssureBizBillListUICTEx.class);

    private IAssureBill iAssureBill = null;

    private IExternalAssureBizBill iExternalAssureBizBill = null;

    /* 存储选中行内码id */
    private static List<String> IDS = new ArrayList<String>();

    public ExternalAssureBizBillListUICTEx() throws Exception {
        super();
    }

    @Override
    public void onLoad() throws Exception {
        this.btnapprovex.setVisible(true);
        this.btnapprovex.setEnabled(true);
        this.btnunapprovex.setVisible(true);
        this.btnunapprovex.setEnabled(true);

        super.onLoad();
    }

    @Override
    public void actionApprovex_actionPerformed(ActionEvent e) throws Exception {

        int res = MsgBox.showConfirm3("~~确定进行审批通过操作么？");

        if (res == 0) {
            initSelectData();
            initInstance();

            if (IDS != null && IDS.size() > 0) {
                logger.info("************************审批通过 START****************");
                Iterator<String> iterator = IDS.iterator();
                while (iterator.hasNext()) {
                    updateData((String) iterator.next(), 1);
                }
            }

            super.actionApprovex_actionPerformed(e);
        }

    }

    @Override
    public void actionUnApprovex_actionPerformed(ActionEvent e) throws Exception {

        int res = MsgBox.showConfirm3("~~确定进行反审批操作么？");
        if (res == 0) {
            initSelectData();
            initInstance();

            if (IDS != null && IDS.size() > 0) {
                logger.info("************************反审核 START****************");
                logger.info("************************反审核 共 " + IDS.size() + " 条");
                Iterator<String> iterator = IDS.iterator();
                while (iterator.hasNext()) {
                    updateData((String) iterator.next(), 0);
                }
            }
            super.actionUnApprovex_actionPerformed(e);
        }

    }

    /**
     * <p>
     * Title: updateData
     * </p>
     * <p>
     * Description: 更新数据
     * </p>
     * 
     * @param uuid 选中的更新担保单余额行内码
     * @param method 方法源 1:审批 0 反审批
     * @throws BOSException
     * @throws EASBizException
     */
    private void updateData(String uuid, int method) throws BOSException, EASBizException {

        if (StringUtils.isEmpty(uuid)) {
            logger.info(this.getClass().getName() + "_updateData() 参数uuid为空!");
            return;
        }

        ExternalAssureBizBillInfo info = iExternalAssureBizBill
                .getExternalAssureBizBillInfo(new ObjectUuidPK(uuid));
        BOSUuid externalAssureUuid = info.getId();
        String billNumber = info.getBillNumber();// 担保单号
        String typeValue = info.getType().getValue();// 款项性质值 借款 1 还款 -1
        String typeAlias = info.getType().getAlias();// 款项性质名称
        BigDecimal money = info.getMoney();// 变动金额

        AssureBillInfo assureBillInfo = getAssureBillInfo(billNumber);
        BOSUuid assureBillUuid = assureBillInfo.getId();
        BigDecimal bizLocalBalance = assureBillInfo.getBizLocalBalance();// 被担保业务余额（折本位币）
        BigDecimal assurePercent = assureBillInfo.getAssurePercent();// 担保比例

        /*
         * 审批通过更新规则： 借款（1）：新被担保业务余额 = 被担保业务余额 +(1 x 变动金额）； 还款（-1）：新被担保业务余额 = 被担保业务余额 +(-1 x 变动金额）；
         * 反审核更新规则：审批通过逻辑反向操作。 担保责任 = 新被担保业务余额 x 担保比例
         */
        BigDecimal newBizLocalBalance = new BigDecimal(0.00); // 新被担保业务余额

        if (method == 1) {
            info.setName("已审批");
            // 审核通过
            newBizLocalBalance = bizLocalBalance.add(money.multiply(new BigDecimal(typeValue)));
        } else {
            info.setName("反审批");

            if ("借款".equals(typeAlias)) {
                newBizLocalBalance = bizLocalBalance.add(money.multiply(new BigDecimal(-1)));
            } else {
                // 还款
                newBizLocalBalance = bizLocalBalance.add(money.multiply(new BigDecimal(1)));
            }
        }
        BigDecimal newAssureResAmount = newBizLocalBalance
                .multiply(assurePercent.divide(new BigDecimal(100)));

        assureBillInfo.setBizLocalBalance(newBizLocalBalance);
        assureBillInfo.setAssureResAmount(newAssureResAmount);

        updateAssureBillInfo(assureBillUuid, assureBillInfo);
        updateExternalAssureBillInfo(info, externalAssureUuid);

    }

    /**
     * <p>
     * Title: updateExternalAssureBillInfo
     * </p>
     * <p>
     * Description: 更新对外担保业务信息
     * </p>
     * 
     * @param info
     * @param externalAssureUuid
     * @throws BOSException
     * @throws EASBizException
     */
    private void updateExternalAssureBillInfo(ExternalAssureBizBillInfo info, BOSUuid externalAssureUuid)
            throws BOSException, EASBizException {
        iExternalAssureBizBill.update(new ObjectUuidPK(externalAssureUuid), info);
    }

    /**
     * <p>
     * Title: getAssureBillInfo
     * </p>
     * <p>
     * Description: 根据担保单号获取其对应的担保单信息
     * </p>
     * 
     * @param billNumber 担保单号
     * @return
     * @throws BOSException
     */
    private AssureBillInfo getAssureBillInfo(String billNumber) throws BOSException {

        iAssureBill = getAssureBillInstance();

        AssureBillCollection assureBillCollection = iAssureBill.getAssureBillCollection(" where number = '"
                + billNumber + "'");

        if (assureBillCollection != null && assureBillCollection.size() > 0) {
            return assureBillCollection.get(0);
        }

        return null;
    }

    /**
     * <p>
     * Title: updateAssureBillInfo
     * </p>
     * <p>
     * Description: 更新担保单信息
     * </p>
     * 
     * @param assureBillUuid
     * @param assureBillInfo
     */
    private void updateAssureBillInfo(BOSUuid assureBillUuid, AssureBillInfo assureBillInfo) {

        try {
            iAssureBill.update(new ObjectUuidPK(assureBillUuid), assureBillInfo);
        } catch (EASBizException e) {
            logger.error(this.getClass().getName() + "_updateAssureBillInfo 更新担保单信息 ERROR! 参数：担保单内码 "
                    + assureBillUuid.toString());
            e.printStackTrace();
        } catch (BOSException e) {
            e.printStackTrace();
        }
    }

    /**
     * 
     * <p>
     * Title: initSelectData
     * </p>
     * <p>
     * Description: 获取列表选中行内码集->IDS
     * </p>
     */
    private void initSelectData() {
        IDS.clear();

        int size = this.tblMain.getSelectManager().size();

        if (size < 1) {
            MsgBox.showWarning("~~还没有选择数据！");
            return;
        }

        for (int i = 0; i < size; i++) {
            KDTSelectBlock selectBlock = this.tblMain.getSelectManager().get(i);
            for (int j = selectBlock.getTop(); j <= selectBlock.getBottom(); j++) {
                String id = (String) tblMain.getRow(j).getCell("id").getValue();
                IDS.add(id);
            }
        }
    }

    private void initInstance() throws BOSException {
        iAssureBill = getAssureBillInstance();
        iExternalAssureBizBill = getExternalAssureBillInstance();
    }

    private IAssureBill getAssureBillInstance() throws BOSException {
        return (iAssureBill != null) ? iAssureBill : AssureBillFactory.getRemoteInstance();
    }

    private IExternalAssureBizBill getExternalAssureBillInstance() throws BOSException {
        return (iExternalAssureBizBill != null) ? iExternalAssureBizBill : ExternalAssureBizBillFactory
                .getRemoteInstance();
    }

}
